package com.lys.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lys.eduservice.entity.EduSubject;
import com.lys.eduservice.entity.excel.SubjectData;
import com.lys.eduservice.entity.subject.OneSubject;
import com.lys.eduservice.entity.subject.TwoSubject;
import com.lys.eduservice.listener.SubjectExcelListener;
import com.lys.eduservice.mapper.EduSubjectMapper;
import com.lys.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author lys
 * @since 2022-06-28
 */
@Service
@Slf4j
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询一级分类
        LambdaQueryWrapper<EduSubject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSubject::getParentId,"0");
        List<EduSubject> eduSubjectList1 = baseMapper.selectList(queryWrapper);

        //查询二级分类
        LambdaQueryWrapper<EduSubject> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.ne(EduSubject::getParentId,"0");
        List<EduSubject> eduSubjectList2 = baseMapper.selectList(queryWrapper1);

        OneSubject oneSubject = null;

        List<OneSubject> oneSubjectList = new ArrayList<>();
        //封装一级分类
        for (EduSubject eduSubject1 : eduSubjectList1) {
            oneSubject = new OneSubject();
            oneSubject.setId(eduSubject1.getId());
            oneSubject.setTitle(eduSubject1.getTitle());

            //封装二级分类
            TwoSubject twoSubject =null;
            List<TwoSubject> twoSubjectList = new ArrayList<>();
            for (EduSubject eduSubject2 : eduSubjectList2) {
                twoSubject =new TwoSubject();
                twoSubject.setId(eduSubject2.getId());
                twoSubject.setTitle(eduSubject2.getTitle());
                if (eduSubject2.getParentId().equals(oneSubject.getId())){
                    twoSubjectList.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjectList);
            oneSubjectList.add(oneSubject);
        }

        return oneSubjectList;
    }
}
